from fastapi import APIRouter, HTTPException
from typing import List, Optional, Dict, Any
from pydantic import BaseModel
from utils import attendance_records_curd
import sqlite3

router = APIRouter(
    tags=["attendance-records"]
)

class AttendanceRecordBase(BaseModel):
    employee_id: str
    date: str
    weekday: str
    morning_on_duty: str
    noon_off_duty: str
    afternoon_off_duty: str
    night_off_duty: str
    noon_work_hours: float
    afternoon_work_hours: float
    day_total_work_hours: float
    night_work_hours: float
    overtime_hours: float
    attendance_type_id: int
    overtime_type: float

class AttendanceRecordCreate(AttendanceRecordBase):
    pass

class AttendanceRecord(AttendanceRecordBase):
    record_id: int
    employee_name: Optional[str] = None
    
    class Config:
        from_attributes = True

class BatchCreateResponse(BaseModel):
    created_records: List[AttendanceRecord]
    skipped_count: int
    message: str

class BatchUpdateRequest(BaseModel):
    record_ids: List[int]
    update_data: Dict[str, Any]

class BatchUpdateResponse(BaseModel):
    updated_count: int
    total_count: int
    message: str

class BatchDeleteRequest(BaseModel):
    record_ids: List[int]

class BatchDeleteResponse(BaseModel):
    deleted_count: int
    total_count: int
    message: str

@router.get("/", response_model=List[AttendanceRecord])
async def get_attendance_records():
    """获取所有考勤记录"""
    return attendance_records_curd.get_all_attendance_records()

@router.get("/{record_id}", response_model=AttendanceRecord)
async def get_attendance_record(record_id: int):
    """获取指定考勤记录"""
    record = attendance_records_curd.get_attendance_record(record_id)
    if not record:
        raise HTTPException(status_code=404, detail="Attendance record not found")
    return record

@router.post("/", response_model=AttendanceRecord)
async def create_attendance_record(record: AttendanceRecordCreate):
    """创建新考勤记录"""
    try:
        return attendance_records_curd.create_attendance_record(record.dict())
    except sqlite3.IntegrityError as e:
        raise HTTPException(status_code=400, detail=f"Invalid employee_id or attendance_type_id: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@router.put("/{record_id}", response_model=AttendanceRecord)
async def update_attendance_record(record_id: int, record: AttendanceRecordCreate):
    """更新考勤记录"""
    try:
        updated_record = attendance_records_curd.update_attendance_record(record_id, record.dict())
        if not updated_record:
            raise HTTPException(status_code=404, detail="Attendance record not found")
        return updated_record
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@router.delete("/{record_id}")
async def delete_attendance_record(record_id: int):
    """删除考勤记录"""
    if not attendance_records_curd.delete_attendance_record(record_id):
        raise HTTPException(status_code=404, detail="Attendance record not found")
    return {"message": "Attendance record deleted successfully"}

@router.post("/batch", response_model=BatchCreateResponse)
async def batch_create_attendance_records(records: List[AttendanceRecordCreate]):
    """批量创建考勤记录"""
    try:
        records_data = [record.dict() for record in records]
        created_records = attendance_records_curd.batch_create_attendance_records(records_data)
        
        # 计算跳过的记录数
        skipped_count = len(records) - len(created_records)
        
        # 构建响应消息
        message = f"成功创建 {len(created_records)} 条记录"
        if skipped_count > 0:
            message += f"，跳过 {skipped_count} 条重复记录"
        
        return {
            "created_records": created_records,
            "skipped_count": skipped_count,
            "message": message
        }
    except sqlite3.IntegrityError as e:
        raise HTTPException(status_code=400, detail=f"Invalid employee_id or attendance_type_id: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@router.patch("/batch", response_model=BatchUpdateResponse)
async def batch_update_attendance_records(request: BatchUpdateRequest):
    """批量更新考勤记录"""
    try:
        updated_count = attendance_records_curd.batch_update_attendance_records(request.record_ids, request.update_data)
        
        # 构建响应消息
        message = f"成功更新 {updated_count}/{len(request.record_ids)} 条记录"
        
        return {
            "updated_count": updated_count,
            "total_count": len(request.record_ids),
            "message": message
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@router.post("/batch/delete", response_model=BatchDeleteResponse)
async def batch_delete_attendance_records(request: BatchDeleteRequest):
    """批量删除考勤记录"""
    try:
        deleted_count = attendance_records_curd.batch_delete_attendance_records(request.record_ids)
        
        # 构建响应消息
        message = f"成功删除 {deleted_count}/{len(request.record_ids)} 条记录"
        
        return {
            "deleted_count": deleted_count,
            "total_count": len(request.record_ids),
            "message": message
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}") 